using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace Obsady
{
    class CUtils
    {
        const string kSeparator = "\n";
        const string kSep = "|";
        // Create a new instance of the RijndaelManaged
        // class.  This generates a new key and initialization 
        // vector (IV).
        RijndaelManaged myRijndael = new RijndaelManaged();
        byte[] encrypted;

        public void parseTags(List<string> aTags, List<CMatch> aMatch)
        {
            const int kRegionalMatchCount = 14;
            int lastRegianalGame = aTags.IndexOf("PLKK");
            for (int i = 0; i + kRegionalMatchCount <= lastRegianalGame; i += kRegionalMatchCount)
            {
                CMatch match = new CMatch(aTags[i + 0], aTags[i + 1], aTags[i + 2], aTags[i + 3], aTags[i + 4], aTags[i + 5], aTags[i + 6], aTags[i + 7], aTags[i + 8], aTags[i + 9], aTags[i + 10], aTags[i + 11], aTags[i + 12], aTags[i+13]);
                aMatch.Add(match);
            }
            aMatch.RemoveAt(0);
            const int kPLKKMatchCount = 14;
            int matchCount = aMatch.Count;
            int lastGame = aTags.IndexOf("Wyznaczenia");
            for (int i = lastRegianalGame + 1; i + kPLKKMatchCount <= lastGame; i += kPLKKMatchCount)
            {
                CMatch match = new CMatch(aTags[i + 0], aTags[i + 1], aTags[i + 2], aTags[i + 3], aTags[i + 4], aTags[i + 5], aTags[i + 6], aTags[i + 7], aTags[i + 8], aTags[i + 9], aTags[i + 10], aTags[i + 11], aTags[i + 12], aTags[i + 13]);
                aMatch.Add(match);
            }
            aMatch.RemoveAt(matchCount); // remove labels            
        }

        public void parse(string aStr, List<string> aTags)
        {
            int pos = 0;
            int last = 0;

            while (pos < aStr.Length)
            {
                pos = aStr.IndexOf(kSep, pos);
                string buf = aStr.Substring(last, pos - last);
                buf = buf.Replace(kSep, ""); //skip separator
                aTags.Add(buf);
                last = pos++;
            }
        }

        public void saveToFile(string aStr, string aFilename)
        {
            FileStream fs = new FileStream(aFilename, FileMode.Create);
            fs.Close();
            StreamWriter sw = new StreamWriter(aFilename, false, Encoding.Default);
            sw.Write(aStr);
            sw.Close();            
        }

        public void saveToFile(byte [] aStr, string aFilename)
        {
            FileStream fs = new FileStream(aFilename, FileMode.Create);
            fs.Close();
            StreamWriter sw = new StreamWriter(aFilename, false, Encoding.ASCII);
            foreach (byte sign in aStr)
            {
                sw.Write(aStr.ToString());
            }
            sw.Close();
        }

        public void saveToFile(ref List<string> aStr, string aFilename)
        {
            string buffer = "";
            foreach (string str in aStr)
            {
                buffer += str + kSeparator;
            }
            saveToFile(buffer, aFilename);
        }

        //delegate
        private bool whiteSign(string aStr)
        {
            if ("" == aStr)
                return true;
            else
                return false;
        }
        
        public void clearAll(List<string> aTags)
        {
            //clear white lines
            aTags.RemoveAll(whiteSign);
            aTags.RemoveAt(0);
            aTags.RemoveAt(0);
        }

        public bool fileExist(string path)
        {
            return File.Exists(path);
        }

        public void saveAuthToFile(string filename, string login, string password)
        {
            string original = login + "|" + password;            

            // Encrypt the string to an array of bytes.
            //encrypted = encryptStringToBytes_AES(original, myRijndael.Key, myRijndael.IV);
            
            saveToFile(original, filename);
        }

        public void readAuthFromFile(string filename, ref string login, ref string password)
        {
            //byte[] encrypted = loadTextFromFile(filename);
            // Decrypt the bytes to a string.
           // string buf = decryptStringFromBytes_AES(encrypted, myRijndael.Key, myRijndael.IV);
            string buf = loadTextFromFile(filename);
            if (null == buf)
                return;            
            //buf = decode13(buf);
            int pos = buf.IndexOf("|");
            if (-1 == pos)
                return;
            login = buf.Substring(0, pos);
            password = buf.Substring(pos + 1, buf.Length - (pos + 1));
        }

        private string loadTextFromFile(string aFilename)
        {
            try
            {
                StreamReader streamReader = new StreamReader(aFilename);
                String str = streamReader.ReadToEnd();
                streamReader.Close();
                return str;
            }
            catch(System.IO.FileNotFoundException)
            {
                return null;
            }
        }

        private string code13(string str)
        {
            if (str != null)
            {
                for (int i = 0; i < str.Length; i++)
                {
                    char c = str[i];
                    str = str.Insert(i, Convert.ToString(c + 13));
                }
            }
            return str;
        }

        private string decode13(string str)
        {
            if (str != null)
            {
                for (int i = 0; i < str.Length; i++)
                {
                    char c = str[i];
                    str.Insert(i, Convert.ToString(c - 13));
                }              
            }
            return str;
        }

        private byte[] encryptStringToBytes_AES(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            // Declare the stream used to encrypt to an in memory
            // array of bytes.
            MemoryStream msEncrypt = null;

            // Declare the RijndaelManaged object
            // used to encrypt the data.
            RijndaelManaged aesAlg = null;

            try
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new RijndaelManaged();
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create an encrypto to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                msEncrypt = new MemoryStream();
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            // Return the encrypted bytes from the memory stream.
            return msEncrypt.ToArray();
        }
        
        private string decryptStringFromBytes_AES(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            try
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new RijndaelManaged();
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            return plaintext;
        }

    }
}
